<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="loginName">
      <Input v-model="form.loginName" :maxlength="11" @on-keyup="filterPhone" placeholder="请输入手机号">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password" class="login_ps_mg">
      <Input type="password" v-model="form.password" @on-keyup="filterSpace" :maxlength="16" placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
  </Form>
</template>
<script>
import { checkPhone } from '@/libs/validate'
export default {
  name: 'LoginForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 8, message: '密码长度不能小于8位', trigger: 'blur' }
        ]
      }
    }
  },
  data () {
    return {
      form: {
        loginName: '',
        password: ''
      }
    }
  },
  computed: {
    rules () {
      return {
        loginName: this.userNameRules,
        password: this.passwordRules
      }
    }
  },
  methods: {
    filterPhone () {
      this.form.loginName = this.form.loginName.replace(/[^0-9]+/g, '')
    },
    filterSpace () {
      this.form.password = this.form.password.replace(/\s+/g, '')
    },
    handleSubmit () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$emit('on-success-valid', {
            loginName: this.form.loginName,
            password: this.form.password
          })
        }
      })
    }
  }
}
</script>
<style lang="less">
.login_ps_mg{
  margin-bottom: 32px;
}
</style>
